<?php
require_once(TEMPLATEPATH . '/admin.php');
add_custom_background();
/* add multilanguage */
function theme_init(){
	load_theme_textdomain('may701', get_template_directory() . '/languages');
}
add_action ('init', 'theme_init');
/* end  */
if ( function_exists('register_sidebar') )
    register_sidebar(array(
        'before_widget' => '<div class="%2$s">',
        'after_widget' => '</div>',
        'before_title' => '<h3 class="wd-title">',
        'after_title' => '</h3>',
    ));

if ( function_exists('register_sidebar') )
    register_sidebar(array(
    	'id' => 'widget_tools',
    	'name' => 'widget_tools',
        'before_widget' => '<div class="%2$s">',
        'after_widget' => '</div>',
        'before_title' => '<h3 class="wd-title">',
        'after_title' => '</h3>',
    ));
if ( function_exists('register_sidebar') )
    register_sidebar(array(
    	'id' => 'img_carousel',
    	'name' => 'img_carousel',
        'before_widget' => '<div class="%2$s">',
        'after_widget' => '</div>',
        'before_title' => '<h3 class="wd-title">',
        'after_title' => '</h3>',
    ));
/* add admin toolbar */
show_admin_bar(false);
/* end add admin toolbar */
/* page navi */
function pagenavi( $p = 2 ) {
if ( is_singular() ) return;
global $wp_query, $paged;
$max_page = $wp_query->max_num_pages;
if ( $max_page == 1 ) return;
if ( empty( $paged ) ) $paged = 1;
if ( $paged > 1 ) p_link( $paged - 1, '上一页', '上一页' );
if ( $paged > $p + 1 ) p_link( 1, '最前页' );
if ( $paged > $p + 2 ) echo '<span class="page-numbers">...</span>';
for( $i = $paged - $p; $i <= $paged + $p; $i++ ) {
if ( $i > 0 && $i <= $max_page ) $i == $paged ? print "<span class='page-numbers current'>{$i}</span> " : p_link( $i );
}
if ( $paged < $max_page - $p - 1 ) echo '<span class="page-numbers">...</span>';
if ( $paged < $max_page - $p ) p_link( $max_page, '最末页' );
if ( $paged < $max_page ) p_link( $paged + 1,'下一页', '下一页' );
}
function p_link( $i, $title = '', $linktype = '' ) {
if ( $title == '' ) $title = "第 {$i} 页";
if ( $linktype == '' ) { $linktext = $i; } else { $linktext = $linktype; }
echo "<a class='page-numbers' href='", esc_html( get_pagenum_link( $i ) ), "' title='{$title}'>{$linktext}</a> ";
}
/* end page navi */
//--start daohang----
register_nav_menus(array(    'primary' => 'primary'));
//--end ----------------------------------------
// function about feed
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'index_rel_link');
add_theme_support( 'automatic-feed-links' );
/* mail tips by yqc */
 function comment_mail_notify($comment_id) {
     $comment = get_comment($comment_id);
     $content=$comment->comment_content;
     $match_count=preg_match_all('/<a href="#comment-([0-9]+)?" rel="nofollow">/si',$content,$matchs);
     if($match_count>0){
         foreach($matchs[1] as $parent_id){
             SimPaled_send_email($parent_id,$comment);
         }
     }elseif($comment->comment_parent!='0'){
         $parent_id=$comment->comment_parent;
         SimPaled_send_email($parent_id,$comment);
     }else return;
 }
 add_action('comment_post', 'comment_mail_notify');
 function SimPaled_send_email($parent_id,$comment){
     $admin_email = get_bloginfo ('admin_email');
     $parent_comment=get_comment($parent_id);
     $author_email=$comment->comment_author_email;
     $to = trim($parent_comment->comment_author_email);
     $spam_confirmed = $comment->comment_approved;
     if ($spam_confirmed != 'spam' && $to != $admin_email && $to != $author_email) {
         $wp_email = 'no-reply@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME']));
         $subject = _e('xg_mail_ninzai','may701') . get_option("blogname") . _e('xg_mail_ylhy','may701');
         $message = '<div style="background-color:#eef2fa;border:1px solid #d8e3e8;color:#111;padding:0 15px;-moz-border-radius:5px;-webkit-border-radius:5px;-khtml-border-radius:5px;">
             <p>' . trim(get_comment($parent_id)->comment_author) . ','._e('xg_mail_nh','may701').'</p>
             <p>'._e('xg_mail_ncz','may701') . get_the_title($comment->comment_post_ID) . _e('xg_mail_dly','may701').'<br />'
             . trim(get_comment($parent_id)->comment_content) . '</p>
             <p>' . trim($comment->comment_author) . _e('xg_mail_gndhf','may701').'<br />'
             . trim($comment->comment_content) . '<br /></p>
             <p>'._e('xg_mail_nkydj','may701').' <a href="' . htmlspecialchars(get_comment_link($parent_id,array("type" => "all"))) . '">'._e('xg_mail_ckwznr','may701').'</a></p>
             <p>'._e('xg_mail_hyzdgl','may701').' <a href="' . get_option('home') . '">' . get_option('blogname') . '</a></p>
             <p>'._e('xg_mail_cyjzdfc','may701').'</p></div>';
         $from = "From: \"" . get_option('blogname') . "\" <$wp_email>";
         $headers = "$from\nContent-Type: text/html; charset=" . get_option('blog_charset') . "\n";
         wp_mail( $to, $subject, $message, $headers );
     }
 }
 function add_checkbox() {
	echo '<span id="cb"><input type="checkbox" name="comment_mail_notify" id="comment_mail_notify" value="comment_mail_notify" checked="checked" style="margin-top:20px;" /><label for="comment_mail_notify" style="color: #888;">' . _e('xg_mail_yrhftzw','may701') . '</label></span>';
}
add_action('comment_form', 'add_checkbox');
/* ramdom newest relate */
function my_get_posts($orderby = '', $plusmsg = '') {
    $get_posts = query_posts('posts_per_page=7&ignore_sticky_posts=1&orderby='.$orderby);
    foreach ($get_posts as $get_post) {
            $output = '';
            $post_date = mysql2date('y-m-d', $get_post->post_date);
            $commentcount = '('.$get_post->comment_count.')';
            $post_title = htmlspecialchars(stripslashes($get_post->post_title));
            $permalink = get_permalink($get_post->ID);
            $output .= '<li><a href="' . $permalink . '" title="'.$post_title.'">' . $post_title . '</a>'.'<span>'.$$plusmsg.'</span>'.'</li>';
            echo $output;
        }
    wp_reset_query();
}
/* end */
/* psot views */
function setPostViews($postID){ 
$count_key = 'post_views_count';  
$count = get_post_meta($postID, $count_key, true);  
if($count=='')
{  
	$count = 0;  
	delete_post_meta($postID, $count_key);  
	add_post_meta($postID, $count_key, '0');  
}  
else
{  
	$count++;  
	update_post_meta($postID, $count_key, $count);  
}  
}
function getPostViews($postID){ 
$count_key = 'post_views_count';  
$count = get_post_meta($postID, $count_key, true);  
if($count=='')
{  
	delete_post_meta($postID, $count_key);  
	add_post_meta($postID, $count_key, '0');  
	return _e('no view','may701');  
}  
return $count;  
} 
/* end post views */
//--------------start google favicon--------------------------
function my_bookmarks($bookmarks, $args = '' ) {
	$defaults = array(
		'show_updated' => 0, 'show_description' => 0,
		'show_images' => 1, 'show_name' => 0,
		'before' => '<li>', 'after' => '</li>', 'between' => "\n",
		'show_rating' => 0, 'link_before' => '', 'link_after' => '','nofollow' =>0
	);

	$r = wp_parse_args( $args, $defaults );
	extract( $r, EXTR_SKIP );

	$output = ''; // Blank string to start with.

	foreach ( (array) $bookmarks as $bookmark ) {
		if ( !isset($bookmark->recently_updated) )
			$bookmark->recently_updated = false;
		$output .= $before;
		if ( $show_updated && $bookmark->recently_updated )
			$output .= get_option('links_recently_updated_prepend');

		$the_link = '#';
		if ( !empty($bookmark->link_url) )
			$the_link = clean_url($bookmark->link_url);

		$rel = ' rel="external';
		if ($nofollow)
			$rel .= ' nofollow';
		if ( '' != $bookmark->link_rel )
			$rel .= ' ' . $bookmark->link_rel;
		$rel .= '"';

		$desc = attribute_escape(sanitize_bookmark_field('link_description', $bookmark->link_description, $bookmark->link_id, 'display'));
		$name = attribute_escape(sanitize_bookmark_field('link_name', $bookmark->link_name, $bookmark->link_id, 'display'));
 		$title = $desc;

		if ( $show_updated )
			if ( '00' != substr($bookmark->link_updated_f, 0, 2) ) {
				$title .= ' (';
				$title .= sprintf(__('Last updated: %s'), date(get_option('links_updated_date_format'), $bookmark->link_updated_f + (get_option('gmt_offset') * 3600)));
				$title .= ')';
			}

		if ( '' != $title )
			$title = ' title="' . $title . '"';

		$alt = ' alt="' . $name . '"';

		$target = $bookmark->link_target;
		if ( '' != $target )
			$target = ' target="' . $target . '"';

		$output .= '<a href="' . $the_link . '"' . $rel . $title . $target. '>';

		$output .= $link_before;

		if ( $show_images ) {
			if ( $bookmark->link_image != null) {
				if ( strpos($bookmark->link_image, 'http') !== false )
					$output .= "<img src=\"$bookmark->link_image\" $alt $title />";
				else 
					$output .= "<img src=\"" . get_option('siteurl') . "$bookmark->link_image\" $alt $title />";
			} else {
				if (preg_match('/^(https?:\/\/)?([^\/]+)/i',$the_link,$URI)) {
					$domains = $URI[2];
				}else{
					$domains = "example.com";
				}
				$output .= "<img src=\"http://www.google.com/s2/favicons?domain=$domains\" $alt $title />";
			}
		}

		$output .= $name;
		$output .= $link_after;
		$output .= '</a>';

		if ( $show_updated && $bookmark->recently_updated )
			$output .= get_option('links_recently_updated_append');

		if ( $show_description && '' != $desc )
			$output .= $between . $desc;

		if ($show_rating) {
			$output .= $between . sanitize_bookmark_field('link_rating', $bookmark->link_rating, $bookmark->link_id, 'display');
		}

		$output .= "$after\n";
	} // end while

	return $output;
}
//--end google------------------------------------
//---remove some rel for html5-------------------
    foreach(array(
        'rsd_link',//rel="EditURI"
        'index_rel_link',//rel="index"
        'start_post_rel_link',//rel="start"
        'wlwmanifest_link'//rel="wlwmanifest"
    ) as $xx)
    remove_action('wp_head',$xx);
    function the_category_filter($thelist){
        return preg_replace('/rel=".*?"/','rel="tag"',$thelist);
    }   
    add_filter('the_category','the_category_filter');
//---end remove-----
//---friend page---------------------------------
function my_list_bookmarks($args = '') {
	$defaults = array(
		'orderby' => 'name', 'order' => 'ASC',
		'limit' => -1, 'category' => '', 'exclude_category' => '',
		'category_name' => '', 'hide_invisible' => 1,
		'show_updated' => 0, 'echo' => 1,
		'categorize' => 1, 'title_li' => __('Bookmarks'),
		'title_before' => '<h2>', 'title_after' => '</h2>',
		'category_orderby' => 'name', 'category_order' => 'ASC',
		'class' => 'linkcat', 'category_before' => '<li id="%id" class="%class">',
		'category_after' => '</li>','nofollow' => 0
	);

	$r = wp_parse_args( $args, $defaults );
	extract( $r, EXTR_SKIP );

	$output = '';

	if ( $categorize ) {
		//Split the bookmarks into ul's for each category
		$cats = get_terms('link_category', array('name__like' => $category_name, 'include' => $category, 'exclude' => $exclude_category, 'orderby' => $category_orderby, 'order' => $category_order, 'hierarchical' => 0));

		foreach ( (array) $cats as $cat ) {
			$params = array_merge($r, array('category'=>$cat->term_id));
			$bookmarks = get_bookmarks($params);
			if ( empty($bookmarks) )
				continue;
			$output .= str_replace(array('%id', '%class'), array("linkcat-$cat->term_id", $class), $category_before);
			$catname = apply_filters( "link_category", $cat->name );
			$output .= "$title_before$catname$title_after\n\t<ul class='xoxo blogroll'>\n";
			$output .= my_bookmarks($bookmarks, $r);
			$output .= "\n\t</ul>\n$category_after\n";
		}
	} else {
		//output one single list using title_li for the title
		$bookmarks = get_bookmarks($r);

		if ( !empty($bookmarks) ) {
			if ( !empty( $title_li ) ){
				$output .= str_replace(array('%id', '%class'), array("linkcat-$category", $class), $category_before);
				$output .= "$title_before$title_li$title_after\n\t<ul class='xoxo blogroll'>\n";
				$output .= my_bookmarks($bookmarks, $r);
				$output .= "\n\t</ul>\n$category_after\n";
			} else {
				$output .= my_bookmarks($bookmarks, $r);
			}
		}
	}

	$output = apply_filters( 'wp_list_bookmarks', $output );

	if ( !$echo )
		return $output;
	echo $output;
}
//---end friend----
/* expert */
function twentyeleven_custom_excerpt_more( $output ) {
	if ( !is_attachment() ) {
		if( !has_excerpt() ){
			$output = mb_strimwidth($output,0,300);
		}
	}
	return $output;
}
add_filter( 'get_the_excerpt', 'twentyeleven_custom_excerpt_more' );
//--start comment frm---
function labq_comment($comment, $args, $depth) {
   $GLOBALS['comment'] = $comment;
   global $commentcount;
   $page = ( !empty($in_comment_loop) ) ? get_query_var('cpage') : get_page_of_comment( $comment->comment_ID, $args );
   $cpp=get_option('comments_per_page');
   if(!$commentcount) 
   {if ($page > 1) {$commentcount = $cpp * ($page - 1);} else {$commentcount = 0;}}
?>
	<li  id="li-comment" >
		<div class="comment-body">
			<div class="commentmeta">
				<?php echo get_avatar( $comment, $size = '64'); ?>
				<div class="vcard">
					<?php printf(__('%s'), get_comment_author_link()) ?>
				</div>
			</div>
				<?php if ($comment->comment_approved == '0') : ?>
				<em><?php _e('Your comment is awaiting moderation.') ?></em><br />
				<?php endif; ?>
			<div class="commentmetadata">&nbsp;&nbsp;<?php printf(__('%1$s at %2$s'), get_comment_date(),  get_comment_time()) ?>&nbsp;&nbsp;<span><?php if(!$parent_id = $comment->comment_parent) {printf('%1$s'._e('xg_mail_floor','may701'), ++$commentcount);} ?><?php if( $depth > 1){printf('', $depth-1);} ?></span></div>
			<?php comment_text() ?>
			<div class="clear"></div>
			<div class="reply"><?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth'], 'reply_text' => _e('xg_mail_reply','may701')))) ?></div>
		</div>
		<div class="clear"></div>
<?php
}
//--end comment frm---
?>
<?php

//add taxonomy img
add_action( 'init', 'create_img_taxonomy' );
function create_img_taxonomy() {
 $labels = array(
    'name' => _x( 'img_taxonomy', 'taxonomy general name' ),
    'singular_name' => _x( 'img_taxonomy', 'taxonomy singular name' ),
    'search_items' =>  __( 'Search Locations' ),
    'all_items' => __( 'All Locations' ),
    'parent_item' => __( 'Parent Location' ),
    'parent_item_colon' => __( 'Parent Location:' ),
    'edit_item' => __( 'Edit Location' ),
    'update_item' => __( 'Update Location' ),
    'add_new_item' => __( 'Add New Location' ),
    'new_item_name' => __( 'New Location Name' ),
  );
 
  register_taxonomy('img_taxonomy','imgshow',array(
    'hierarchical' => true,
    'labels' => $labels
  ));
}

//post type imgshow
add_action('init', 'custom_imgshow_init');
function custom_imgshow_init() {
    $labels = array(
        'name' => _x('imgshow', 'post type general name'),
        'singular_name' => _x('imgshow', 'post type singular name'),
        'add_new' => _x('添加新图片', 'imgshow'),
        'add_new_item' => __('新图片上墙'),
        'edit_item' => __('Edit imgshow'),
        'new_item' => __('New imgshow'),
        'view_item' => __('View imgshow'),
        'search_items' => __('Search imgshow'),
        'not_found' =>  __('No work found'),
        'not_found_in_trash' => __('No work found in Trash'),
        'parent_item_colon' => '',
        'menu_name' => '照片墙'
    );
 
    $args = array(
        'labels' => $labels,
        'public' => true,
        'publicly_queryable' => true,
        'show_ui' => true,
        'show_in_menu' => true,
        'query_var' => true,
        'rewrite' => false,
        'capability_type' => 'post',
        'has_archive' => true,
        'hierarchical' => false,
        'menu_position' => 5,
        'supports' => array('title','editor','author','thumbnail','excerpt','comments','custom-fields','revisions','page-attributes'),
        'taxonomies' => array('img_taxonomy','post_tag','category')
    );
    register_post_type('imgshow',$args);

}
function custom_post_author_archive($query) {
    if ($query->is_author || $query->is_category)
        $query->set( 'post_type', array('imgshow','post','page') );
    //remove_action( 'pre_get_posts', 'custom_post_author_archive' );
    return $query;
}
add_action('pre_get_posts', 'custom_post_author_archive');
add_action('admin_init', 'flush_rewrite_rules');

//end post type imgshow
?>
<?php   
/**
 * 选项组类型  
 */  
class ClassicOptions {   
    /* -- getOptions函数获取选项组 -- */  
    function getOptions() {   
        // 在数据库中获取选项组   
        $options = get_option('classic_options');   
        // 如果数据库中不存在该选项组, 设定这些选项的默认值, 并将它们插入数据库   
        if (!is_array($options)) {   
            //初始默认数据   
            $options['issmall'] = false;   
            $options['small_title'] = '';          
            // TODO: 在这里追加其他选项             
            update_option('classic_options', $options);   
        }   
        // 返回选项组   
        return $options;   
    }   
    /* -- init函数 初始化 -- */  
    function init() {   
        // 如果是 POST 提交数据, 对数据进行限制, 并更新到数据库   
        if(isset($_POST['classic_save'])) {   
            // 获取选项组, 因为有可能只修改部分选项, 所以先整个拿下来再进行更改   
            $options = ClassicOptions::getOptions();   
            // 数据限制   
            if ($_POST['issmall']) {   
                $options['issmall'] = (bool)true;   
            } else {   
                $options['issmall'] = (bool)false;   
            }   
            $options['small_title'] = stripslashes($_POST['small_title']);   
            // TODO: 在这追加其他选项的限制处理   
            // 更新数据   
            update_option('classic_options', $options);   
        // 否则, 重新获取选项组, 也就是对数据进行初始化   
        } else {   
            ClassicOptions::getOptions();   
        }   
        // 在后台 Design 页面追加一个标签页, 叫 Current Theme Options   
        add_theme_page("主题设置", "主题设置", 'edit_themes', basename(__FILE__), array('ClassicOptions', 'display'));   
    }   
    /* -- 标签页 -- */  
    function display() {   
        $options = ClassicOptions::getOptions();   
?>   
<form method="post" enctype="multipart/form-data" name="classic_form" id="classic_form">   
    <div class="wrap">   
        <h2><?php _e('主题设置', 'classic'); ?></h2>   
        <!-- 设置内容 -->   
        <table class="form-table">   
            <tbody>   
                <tr valign="top">   
                    <th scope="row">   
                        <?php _e('小标题'); ?>   
                        <br/>   
                    </th>   
                    <td>   
                        <!-- 是否显示小标题 -->   
                        <label>   
                            <input name="issmall" type="checkbox" value="checkbox" <?php if($options['issmall']) echo "checked='checked'"; ?> />   
                             <?php _e('显示小标题'); ?>   
                        </label>   
                        <br/>   
                        <!-- 小标题内容 -->   
                        <label>   
                            <input type="text" name="small_title" value="<?php echo($options['small_title']); ?>" size="20" maxlength="20" style="width:40%;font-size:12px;"/><?php _e('这是logo旁边的小标题');?>   
                        </label>   
                    </td>   
                </tr>   
            </tbody>   
        </table>   
        <!-- TODO: 在这里追加其他选项内容 -->   
        <!-- 提交按钮 -->   
        <p class="submit">   
            <input type="submit" name="classic_save" value="<?php _e('保存设置'); ?>" />   
        </p>   
    </div>   
</form>   
<?php   
    }   
}   
/**
 * 登记初始化方法  
 */  
add_action('admin_menu', array('ClassicOptions', 'init'));    
?>
<?php
/*文章配图*/
add_action('save_post', 'custom_add_save');
 function catch_that_image() {
      global $post, $posts;
      $first_img = '';
      ob_start();
      ob_end_clean();
      $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
      $first_img = $matches [1] [0];
      if(empty($first_img)){ //Defines a default image
        $first_img = "/wp-content/themes/Qone/images/default.gif";
      }
      return $first_img;
    }
function custom_add_save($postID){
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return $postID;
    }
    else
    {
        // called after a post or page is saved
        if($parent_id = wp_is_post_revision($postID))
        {
        $postID = $parent_id;
        }
        update_custom_meta($postID, catch_that_image(), 'img_url');
    }
}

function update_custom_meta($postID, $newvalue, $field_name) {
    // To create new meta
    if(!get_post_meta($postID, $field_name)){
    add_post_meta($postID, $field_name, $newvalue);
    }else{
    // or to update existing meta
    update_post_meta($postID, $field_name, $newvalue);
    }
}
?>